package com.serv.admin;

import com.jfinal.aop.Aop;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.validate.Validator;
import com.serv.common.model.sys.User;
import com.serv.common.service.sys.UserService;
import com.serv.util.AjaxObject;
import com.serv.util.Result;

public class AdminValidator extends Validator {
	@Override
	protected void validate(Controller c) {
		setShortCircuit(true);
		String actionKey = getActionKey();
		
		if (actionKey.equals("/doLogin")) validateLogin(c);
		if (actionKey.equals("/doLoginDialog")) validateLogin(c);
	}

	private void validateLogin(Controller c) {
		validateRequired("username","msg","用户名不能为空");
		validateRequired("password","msg","密码不能为空");
		
		boolean captcha = PropKit.getBoolean("user.captcha",false);
		if(captcha == true) {
			validateRequired("captcha","msg","验证码不能为空");
			validateCaptcha("captcha","msg", "验证码错误");
		}
		
		User user = Aop.get(UserService.class).getByUsername(c.getPara("username"));
		if(user == null) addError("msg","用户不存在");
	}
	
	@Override
	protected void handleError(Controller c) {
		String actionKey = getActionKey();
		if (actionKey.equals("/doLogin")){
			Result result = Result.error(c.getAttrForStr("msg"));
			c.renderJson(result);
		}else if (actionKey.equals("/doLoginDialog")){
			AjaxObject result = AjaxObject.newError(c.getAttrForStr("msg"));
			c.renderJson(result);
		}
	}
}
